package com.zz.common.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import com.zz.common.utils.ZLog;

import android.app.Application;
import android.os.Process;

public class BaseApplication extends Application implements CrashController.OnCrashListener {
	
	public static String sCrashPath;

	private static BaseApplication sApplication;
	
	public static BaseApplication getBaseApplication() {
		return sApplication;
	}
	
	public void exit() {
		ArrayList<WeakReference<BaseActivity>> activityStack = BaseActivity.getActivityStack();
		try {
			for(WeakReference<BaseActivity> ref: activityStack) {
				BaseActivity activity = ref.get();
				if(null != activity && !activity.isFinishing()) {
					activity.finish();
				}
			}
		} catch(Exception e) {
			e = null;
		}
		Process.killProcess(Process.myPid());
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		sApplication = this;
		CrashController controller = new CrashController(this, sCrashPath, this);
		Thread.setDefaultUncaughtExceptionHandler(controller);
		ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onCreate: " + this);
	}
	
	@Override
	public void onTerminate() {
		super.onTerminate();
		ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_KEY, "onDestroy: " + this);
	}
	
	@Override	//CrashController.OnCrashListener
	public boolean onCrash(String filePath, CrashController handler) {
		exit();
		return false;
	}
	
	//
	protected void onEnterBackground() {
		ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onEnterBackground: " + this);
	}
	
	//
	protected void onEnterForeground() {
		ZLog.d(BaseConfig.TAG, ZLog.LOG_LEVEL_DEV, "onEnterForeground: " + this);
	}
	
	public static interface IBaseApplicationattachment {
		public BaseApplication getBaseApplication();
	}

}
